package com.medplus.hubdirect.web;

import java.util.List;

import javax.validation.Valid;

import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;

import com.medplus.hubdirect.dao.UserEndPointDAO;
import com.medplus.hubdirect.model.User;

@Controller
@SessionAttributes("user")
public class UserController {
	@Autowired
	private UserEndPointDAO userEndPointDAO;
	
	private Logger logger = org.slf4j.LoggerFactory.getLogger(UserController.class);

	@RequestMapping(value="/user", method=RequestMethod.GET)
	public String listUsers(Model model) {
		logger.info("List Users");
		List<User> users = userEndPointDAO.findUsers();
		model.addAttribute("users", users);
		return "/user/list";
	}

	@RequestMapping(value="/user/new", method=RequestMethod.GET)
	public String setupNewUser(Model model) {
		logger.info("Setup New User");		
		User user = new User();
		model.addAttribute("user", user);
		return "user/newuser";
	}

	@RequestMapping(value="/user/{userId}", method=RequestMethod.GET)
	public String editUser(@PathVariable("userId") int userId, Model model) {
		User user = userEndPointDAO.findUserById(userId);
		model.addAttribute("user", user);		
		return "user/showuser"; 
	}
	
	@RequestMapping(value="/user/new", method=RequestMethod.POST)
	public String AddUser(@Valid User user, BindingResult result, SessionStatus status) {
		logger.info("Add User");
		User entity = userEndPointDAO.save(user);
		
		// Clears @SessionAttributes
		status.setComplete();  
		
		return "redirect:/user/" + entity.getUserListId();
	}
	
}
